package com.xyxy.web;

import com.google.gson.Gson;
import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
import com.xyxy.pojo.User;
import com.xyxy.service.UserService;
import com.xyxy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
    * @Desc: 处理登录功能
    * @param:
    * @return:
    */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        if(loginUser == null){
            //把错误信息和回显的表单项信息保存到request域中
            req.setAttribute("msg","用户或密码错误！");
            req.setAttribute("username",username);

            //如果等于null,说明登录失败,跳回登录页面
            System.out.println("登录失败，用户名不存在！");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else{

            //用session保存用户登录后的信息
            req.getSession().setAttribute("user",loginUser);

            //如果登录成功，跳到成功页面login_success.html
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }
    }

    /**
    * @Desc: 处理注册功能
    * @param:
    * @return:
    */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //用谷歌的验证码
        //1，获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //2，删除session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        // 1、获取请求的参数,表单的name属性值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");//验证码

        //2、检查验证码是否正确
        if (token != null && token.equalsIgnoreCase(code)) {

            //3、如果验证码正确，检查用户名是否可用
            if (userService.isExistsUsername(username)) {
                //如果不可用
                System.out.println("用户名" + username + "已存在！");

                //把信息回显，保存到request域中
                req.setAttribute("msg","用户名已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);

                //跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //如果可用,调用Service保存到数据库,跳到注册成功束面regist_success.html
                userService.registUser(new User(null, username, password, email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //把信息回显，保存到request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);

            //不正确,跳回注册页面
            System.out.println("验证码" + code + "错误!");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    //注销用户
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1,销毁session中用户登录信息（或直接销毁session）
        req.getSession().invalidate();
        //2,重定向回首页或登录页面
        resp.sendRedirect(req.getContextPath());
    }

    //使用ajax请求验证用户名是否已经存在
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求的参数username
        String username = req.getParameter("username");

        //调用userService.existsUsername();
        boolean existsUsername = userService.isExistsUsername(username);

        //把返回的结果封装成为map对象
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);

        //用json格式传给客户端
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);//转换成json字符串

        resp.getWriter().write(json);

    }

}

